/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.digest;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA算法，公钥加密使用私钥解密，私钥加密则用公钥加密
 * 场景描述：
 * <p>
 * 3.1 私钥用于签名，公钥用于验签。
 * 签名与加密作用不同。签名并不是为了保密，而是为了保证这个签名是由特定的某个人（持有私钥的人）签名的，而不是被其他人伪造的签名，
 * 所以私钥的私有性适合用于数字签名。私钥签名后，只能由私钥所对应的公钥进行解密操作，
 * 公钥持有者可通过解密后的信息判断出是否是私钥持有人的签名，也可以根据数字签名的特性判断出数据是否被篡改。
 * <p>
 * 3.2 公钥用于加密，私钥用于解密。
 * 公钥公开，并且一般情况下多人持有，此时若使用私钥加密，则公钥持有人都可对私钥加密后的数据进行解密操作，
 * 数据不安全。使用公钥加密，则只能由私钥进行解密操作，而私钥私有不公开，可保证数据只能由私钥持有人解密，保证数据安全。
 *
 * @author Mr.css 2018-05-23 10:36:29
 */
public class RSA {
    private RSA() {
    }

    private static final String CIPHER_RSA = "RSA";

    /**
     * 获取密钥对，默认长度1024
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws GeneralSecurityException {
        return getKeyPair(1024);
    }

    /**
     * 获取密钥对
     *
     * @param initialize 长度
     * @return 密钥对
     */
    public static KeyPair getKeyPair(int initialize) throws GeneralSecurityException {
        KeyPairGenerator keyPairGen;
        keyPairGen = KeyPairGenerator.getInstance(CIPHER_RSA);
        keyPairGen.initialize(initialize);
        return keyPairGen.generateKeyPair();
    }

    /**
     * 获取公钥字符串
     */
    public static String getPublicKey(KeyPair keyPair) {
        return Base64.encodeString(keyPair.getPublic().getEncoded());
    }

    /**
     * 获取私钥字符串
     */
    public static String getPrivateKey(KeyPair keyPair) {
        return Base64.encodeString(keyPair.getPrivate().getEncoded());
    }

    /**
     * 获取公钥对象
     *
     * @param publicKey 公钥字符串
     * @return 公钥
     * @throws GeneralSecurityException -
     */
    public static PublicKey generatePublicKey(String publicKey) throws GeneralSecurityException {
        byte[] keyBytes = Base64.decodeString(publicKey);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance(CIPHER_RSA);
        return factory.generatePublic(x509EncodedKeySpec);
    }

    /**
     * 获取私钥对象
     *
     * @param privateKey 私钥字符串
     * @return 私钥
     * @throws GeneralSecurityException -
     */
    public static PrivateKey generatePrivateKey(String privateKey) throws GeneralSecurityException {
        byte[] keyBytes = Base64.decodeString(privateKey);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance(CIPHER_RSA);
        return factory.generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * 加密为16进制字符串
     *
     * @param data 数据
     * @param key  公钥/私钥
     * @return encode data
     * @throws GeneralSecurityException encode failed
     */
    public static String encryptHex(String data, Key key) throws GeneralSecurityException {
        return Hex.encodeToString(encrypt(data.getBytes(), key));
    }

    /**
     * 解密16进制字符串
     *
     * @param encryptedData 加密数据
     * @param key           公钥/私钥
     * @return decode data
     * @throws GeneralSecurityException encode failed
     */
    public static String decryptHex(String encryptedData, Key key) throws GeneralSecurityException {
        return new String(decrypt(Hex.decode(encryptedData.toCharArray()), key));
    }

    /**
     * 加密
     *
     * @param data 数据
     * @param key  公钥/私钥
     */
    public static byte[] encrypt(byte[] data, Key key) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param data 数据
     * @param key  公钥/私钥
     */
    public static byte[] decrypt(byte[] data, Key key) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }
}
